import React,{ Component } from 'react';
import {
	StyleSheet,
	View,
	Text,
	TouchableOpacity,
	Image,
	Dimensions,
	Menu,
	ScrollView,
	FlatList,
	Button,
	Alert
} from 'react-native';
import { HeaderDatepicker } from '../../common';
import Axios from '../../axios';
import SideMenu from 'react-native-side-menu';
import { ReportChart }from './ReportChart';

import CheckList from '../../common/CheckList';
import Toast, {DURATION} from 'react-native-easy-toast';


const {width, heihgt} = Dimensions.get('window');

class HeaderRight extends Component{
	render(){
		return (<TouchableOpacity
				onPress={this.props.openMenu}
			>
			<Image
				style={styles.topRightImg}
				source={require('../../assets/images/shaixuan_icon.png')}
			/>
		</TouchableOpacity>)
	}
}

class HeaderLeft extends Component{
	render(){
		return (<TouchableOpacity
				onPress={()=>this.props.goBack()}
			>
			<Image
				style={styles.topLeftImg}
				source={require('../../assets/images/back_icon.png')}
			/>
		</TouchableOpacity>)
	}
}

export default class ReportDetail extends Component{
	constructor(props){
		super(props);
		this.props.navigation.setParams({ sideMenuOpened:false });
		this.conditionValue={};
		this.selectTopValue={};
	}

	state = {
		sideMenuOpened:false,
		dateValue:{},
		dataList:[],
		selectTopList:{},
		conditionList:{}
	}

	getEchartsData(){

		let param = {};
	    let conditionValue = this.conditionValue;
	    let selectTopValue = this.selectTopValue;

	    for(var key1 in conditionValue){
	    	param[key1] = conditionValue[key1];
		}

		for(var key2 in selectTopValue){
	    	param[key2] = selectTopValue[key2];
		}

		let currentDate = this.props.navigation.getParam('currentDate')

		if (currentDate) {
			param.DATE = this.props.navigation.getParam('currentDate').replace(/-/g, '');
		}

	    const parentId = this.props.navigation.getParam('id', 'parentId');

		Axios.ajax({
			url:'/app/getReportDetail',
			data:{
				parentId:parentId,
				param:param
			}
		}).then((res)=>{

			console.log('res',res);
			let _this = this;
			//渲染时间
			this.renderDate(res, _this);

			//渲染top
	        this.renderSelectTop(res, _this);

			//渲染条件
	        this.renderCondition(res, _this);

			//echarts渲染
			this.setState({dataList:res.data.DATA_LIST});
		})

	}


	renderDate(res, _this) {

		let date = res.data.DATE;
		if (date) {
			let minDate = date.minDate;
		    let maxDate = date.maxDate;
			let minDateparam = this.getDateFormat("date",minDate);
			let maxDateparam = this.getDateFormat("date",maxDate);
			let dateValue = {
		        minDate:minDateparam,
		        maxDate:maxDateparam
			}
			this.props.navigation.setParams({dateValue:dateValue});
			this.props.navigation.setParams({currentDate:maxDateparam});
		}
		
	}



	//渲染top
	renderSelectTop(res, _this) {
		//渲染top
		let selectTopList = res.data.SELECT_TOP_LIST;
		
		console.log(selectTopList)

		//找到选中的selectTopId赋值给setState(selectTopId)
		let selectTopListAble = [];
		let selectTopListUnable = []
		selectTopList.map(function(selectTop){
			if(selectTop.ableClick){
				selectTopListAble.push(selectTop)
			}else{
				selectTopListUnable.push(selectTop)
			}

			if (selectTop.isCheck) {
				let selectTopId = selectTop.id;
				let column = selectTop.column;
				_this.selectTopValue[column] = selectTopId;
			}
		})
		let selectTopListNew = selectTopListAble.concat(selectTopListUnable);
		this.setState({selectTopList:selectTopListNew});

	}


    //渲染条件
	renderCondition(res, _this) {
			let conditionListRes = res.data.CONDITION_LIST;
			//默认第一次加载
			if (conditionListRes) {
				for(var i = 0; i < conditionListRes.length; i++) {
					(conditionListRes[i].conditionEnum).map(function(condition,index){
					    let name = condition.name;
						let value = condition.value;
						let column = condition.column;
						if (index == 0) {
							_this.conditionValue[column] = value;
						}
					})
	          	}
				this.setState({conditionList:conditionListRes});
		    }
	}


	//时间格式化
	getDateFormat(mode, date) {
		let newDate = '';
		if (mode === 'date') {
			newDate = date.substr(0,4) + "-" + date.substr(4,2) + "-" +date.substr(6,2);
		}
		return newDate;
	}



	static navigationOptions = ({navigation,navigationOptions})=>{

		return {
			title:"首页",
			headerTitle:<HeaderDatepicker
				dateValue={navigation.getParam('dateValue')}
				currentDate={navigation.getParam('currentDate')}
				onDateChange={(date)=>{
					navigation.setParams({ currentDate:date });
					navigation.state.params.getEchartsData();
				}}

			/>,
			headerRight:<HeaderRight openMenu={()=>navigation.setParams({ sideMenuOpened:!navigation.getParam('sideMenuOpened') })} />,
			headerLeft:<HeaderLeft goBack={()=>navigation.goBack()} />,
			headerStyle:{
				...navigationOptions.headerStyle,
				backgroundColor:"#f54545",
				borderBottomWidth:0
			}
		}
	}

	componentDidMount(){
		this.props.navigation.setParams({getEchartsData:this.getEchartsData.bind(this)})
		this.getEchartsData();

	}

	initMenu = ()=>{

		let conditionList = this.state.conditionList;

		if (conditionList.length > 0) {
				return (

					<View style={styles.menuContainer}>
						<FlatList
							horizontal={false}
			 	       		keyExtractor={(item,index)=>index.toString()}
			           		data={this.state.conditionList}
			    	   		renderItem={({item}) => (
			    	   			<View style={styles.reportCellContentWrap}>
						    		<View style={styles.sideMenuTitle}>
						    			<Image 
											style={{width:16,height:16,marginRight:5}}
											source={require('../../assets/images/shaixuan_icon_cell.png')}
						    			/>
						    			<Text style={styles.sideMenuTitleTxt}>{item.conditionName}</Text>
						    		</View>
						    		<View style={styles.checkListWrap}>
						    			<CheckList 
											data={item.conditionEnum}
											type='radio' //radio和checkbox
											checkClick={(value)=>{
												let name = value.name;
			           							let value2 = value.value;
			           							let column = value.column;
			           							this.conditionValue[column] = value2;
											}}
										/>
						    		</View>
						 		</View>

			    	   		)}
	           			/>
						
						<TouchableOpacity
							onPress={this.onButtonPress}
						>
			           		<View style={styles.sideMenuBtnWrap}>
				           		<Text style={{color:'#fff',fontSize:16}}>提交</Text>
							</View>
						</TouchableOpacity>
				</View>
				)
		} else {
			return <Text></Text>
		}

	}

	render(){
		return(
			<View style={styles.container}>
				<SideMenu
					menu={this.initMenu()}
					isOpen={this.props.navigation.getParam('sideMenuOpened')}     	//抽屉打开/关闭
	                //openMenuOffset={width}     			//抽屉的宽度
	                edgeHitWidth={60}      					//距离屏幕多少距离可以滑出抽屉,默认60
	                menuPosition={"right"}        			//侧边栏的位置
	                disableGestures={false}        			//是否禁用手势滑动抽屉 默认false 允许手势滑动
	                onChange = {(isOpen)=>{
	                	this.props.navigation.setParams({sideMenuOpened:isOpen})
	                }}
				>
			        <View style={styles.container}>
						{/* <Text>{this.props.navigation.getParam("id")+this.props.navigation.getParam("name")}</Text> */}
						{/* 顶部滚动 */}
						<View style={styles.topTabScroll}>
							<ScrollView
								horizontal={true}
								showsHorizontalScrollIndicator={false}
							>
							<FlatList
								horizontal={true}
				 	       		keyExtractor={(item,index)=>index.toString()}
				           		data={this.state.selectTopList}
				    	   		renderItem={({item}) => (
				    	   			item.ableClick?
				    	   			<TouchableOpacity onPress={() => {
					    	   				let selectTopId = item.id;
					    	   				let column = item.column;
					    	   				this.selectTopValue[column] = selectTopId;
					    	   				this.getEchartsData();
					    	   			}}
					    	   		>
				    		            {item.isCheck?
					    		            <View style={[styles.tabCell,styles.tabCellCheck]}>
												<View style={styles.topButton}>
													<Text style={[styles.cellText,styles.cellTitle]}>{item.name}</Text>
													<Text style={styles.cellText}>{item.value}</Text>
												</View>
											</View>
											: 
											<View style={styles.tabCell}>
												<View style={styles.topButton}>
													<Text style={[styles.cellText,styles.cellTitle]}>{item.name}</Text>
													<Text style={styles.cellText}>{item.value}</Text>
												</View>
											</View>
										}
									</TouchableOpacity>
									: 
									<View style={[styles.tabCell,styles.tabCellDisableClick]}>
										<View style={styles.topButton}>
											<Text style={[styles.cellText,styles.cellTitle]}>{item.name}</Text>
											<Text style={styles.cellText}>{item.value}</Text>
											<Image 
												style={{position:'absolute',bottom:5,right:-10,width:20,height:20}}
												source={require("../../assets/images/unable.png")}
											/>
										</View>
									</View>

				    	   		)}
			           		/>
							</ScrollView>
						</View>
						{/* 图表 */}

						<ReportChart dataList={this.state.dataList} />
			        </View>
			    </SideMenu>

			</View>
		)
	}


   /*
	*
	*点击抽屉提交按钮
	*/
	 onButtonPress =  () => {
		this.props.navigation.setParams({ sideMenuOpened:false });
	  	this.getEchartsData();
  	 };
}


const styles = StyleSheet.create({
	topButton:{
		flex:1,
		justifyContent:'center',
		alignItems:'center'
	},
	sideMenuBtnWrap:{
		justifyContent:'center',
		alignItems:'center',
		backgroundColor:'#f54545',
		width:2*width/3,
		marginLeft:-20,
		height:36
	},
	menuContainer:{
		flex : 1,
		paddingLeft:20,
		paddingRight:20,
		backgroundColor:'#fcfcfc'
	},
	sideMenuItem:{
		borderWidth:1,
		borderColor:"#ccc",
		paddingLeft:10,
		paddingTop:5,
		paddingRight:10,
		paddingBottom:5,
		borderRadius:14,
		marginLeft:5,
		marginRight:5
	},
	sideMenuItemTxt:{
		fontSize:16,
		color:'#454545'
	},
	sideMenuTitle:{
		flexDirection:'row',
		paddingBottom:10,
		borderBottomWidth:1,
		borderBottomColor:'#eee',
		marginBottom:10
	},
	sideMenuTitleTxt:{
		fontSize:16,
		color:'#f54545',
	},
	container : {
		flex : 1,
		backgroundColor:'#f5f5f5'
	},
	topRightImg:{
		width:22,
		height:22,
		marginRight:10
	},
	topLeftImg:{
		width:22,
		height:22,
		marginLeft:10
	},
	topTabScroll:{
		backgroundColor:'#fff'
	},
	tabCell:{
		height:100,
		width:140,
		paddingLeft:20,
		paddingRight:20,
		backgroundColor:'#fff',
		borderRightWidth:1,
		borderRightColor:'#d5d5d5',
		borderBottomWidth:4,
		borderBottomColor:'#d5d5d5'
	},
	tabCellCheck:{
		backgroundColor:'#fff',
		borderBottomWidth:4,
		borderBottomColor:'#fc6f6f'
	},
	tabCellDisableClick:{
		backgroundColor:'#f5f5f5'
	},
	cellTitle:{ 
		fontSize:16,
		textAlign:'center'
	},
	cellText:{
		fontSize:16,
		color:'#757575',
		marginTop:5,
		marginBottom:5
	},

	tableIcon:{
		height:40,
		alignItems:'center',
		justifyContent:'center'
	},
	reportCellContentWrap:{
		flex:1,
		justifyContent:"center",
		marginTop:20,
		marginBottom:40
	},
	reportContentTopTxt:{
		textAlign:"center",
		fontSize:14
	},
	reportContentTotal:{
		textAlign:"left",
		fontSize:26,
		color:"#f54545",
		marginTop:10,
		marginBottom:10
	},
	checkListWrap:{
		flex:1,
		flexDirection:"row",
		flexWrap:"wrap",
		justifyContent:"center"
	},
	reportContentBottomWrap:{
		/*marginLeft:width-(2*width/3)-130,*/
		/*textAlign:"left",*/
		flex:1,
		flexDirection:"row",
		justifyContent:"center"
	},

	reportContentBottomTxtCheck:{
		fontSize:14,
		marginRight:10,
		marginLeft:10,
		color:"#f54545"
	},
	reportContentBottomTxt:{
		fontSize:14,
		marginRight:10,
		marginLeft:10,
		color:'#757575'
	}
})
